package com.you.common.webx.service;

import static com.alibaba.citrus.springext.util.DomUtil.and;
import static com.alibaba.citrus.springext.util.DomUtil.name;
import static com.alibaba.citrus.springext.util.DomUtil.sameNs;
import static com.alibaba.citrus.springext.util.DomUtil.subElements;
import static com.alibaba.citrus.springext.util.SpringExtUtil.createManagedList;
import static com.alibaba.citrus.util.StringUtil.trimToNull;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;

import com.alibaba.citrus.springext.support.parser.AbstractNamedBeanDefinitionParser;
import com.alibaba.citrus.springext.util.DomUtil.ElementSelector;
import com.alibaba.citrus.util.StringUtil;
import com.you.common.webx.AuthContext;

public class SecurityMappingService {

    private List unProtectedURLs;

    public void setUnProtectedURLs(List unProtectedURLs) {
        this.unProtectedURLs = unProtectedURLs;
    }

    public boolean checkAuthentication(HttpServletRequest request) {
        if (unProtectedURLs.contains(StringUtil.toCamelCase(request.getRequestURI()))) {
            return true;
        } else {
            return AuthContext.getContext().isLogin();
        }
    }
                                                 
    public static class DefinitionParser extends AbstractNamedBeanDefinitionParser<SecurityMappingService> {

        @Override
        protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {

            ElementSelector unProtectedUrls = and(sameNs(element), name("un-protected-url"));
            List<Object> unProtectedURLs = createManagedList(element, parserContext);
            
            for (Element subElement : subElements(element)) {
                if (unProtectedUrls.accept(subElement)) {
                    
                    String name = trimToNull(subElement.getAttribute("name"));
                    if (name != null) {
                        unProtectedURLs.add(name);
                    }
                }
            }
            
            builder.addPropertyValue("unProtectedURLs", unProtectedURLs);
        }



        @Override
        protected String getDefaultName() {
            return "securityMappingService";
        }

    }
}
